#include <iostream>
#include <string>
#include <fcntl.h>
#include <cerrno>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

enum player
{
    serve, // 写 --- 服务器
    client // 读 --- 客户端
};
const std::string pathname = "./myfifo";
const int size = 4096;

void create_namedpipe()
{
    int ret = mkfifo(pathname.c_str(), 0666);
    if (ret != 0)
    {
        perror("mkfifo");
    }
    std::cout << "create namedpipe sucessfully" << std::endl;
}

int open_serve()
{
    int fd = open(pathname.c_str(), O_WRONLY);
    if (fd < 0)
    {
        return -1;
    }
    return fd;
}
int open_client()
{
    int fd = open(pathname.c_str(), O_RDONLY);
    if (fd < 0)
    {
        return -1;
    }
    return fd;
}
int open_namedpipe(int who)
{
    if (who == serve)
    {
        return open_serve();
    }
    else if (who == client)
    {
        return open_client();
    }

    return -1;
}

void read_namedpipe(int fd)
{
    char buffer[size] = {0};
    int n = read(fd, buffer, sizeof(buffer));

    if (n < 0)
    {
        std::cout << "read_namedpipe fail" << std::endl;
        perror("read_namedpipe: ");
        exit(1);
    }
    buffer[n] = 0;
    std::cout << buffer << std::endl;
}
void write_namedpipe(int fd)
{
    std::string msg = "hello, Linux";
    write(fd, msg.c_str(), msg.size());
}